/*
子密钥的生成
 */
package generate

import (
	"AES/GF"
)


// g 变换
func g(word []byte, rc byte) []byte {
	re := make([]byte, 4)
	for i := 0; i < 4; i++ {
		re[i] = S_Change(word[(i + 1) % 4])
	}
	re[0] = re[0] ^ rc
	return re
}

// 两个字异或
func trick(n1 []byte, n2 []byte) []byte {
	re := make([]byte, len(n1))
	for i := 0; i < len(n1); i++ {
		re[i] = n1[i] ^ n2[i]
	}
	return re
}

// 生成 n 轮的密钥，不包括初始的轮密钥加
func KeyExpansion(priKey *[]byte, n int) [][]byte {
	key := make([][]byte, 0)
	key = append(key, *priKey)
	rc := byte(1)
	for i := 0; i < n; i++ {
		tmp := make([]byte, 0)
		tmp = append(tmp, trick((*priKey)[0:4], g((*priKey)[12:16], rc))...)
		tmp = append(tmp, trick(tmp[0:4], (*priKey)[4:8])...)
		tmp = append(tmp, trick(tmp[4:8], (*priKey)[8:12])...)
		tmp = append(tmp, trick(tmp[8:12], (*priKey)[12:16])...)
		key = append(key, tmp)
		*priKey = tmp
		rc = GF.Multiply(byte(2), rc)
	}
	return key
}


